package br.org.credfaz.ficha.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.org.credfaz.ficha.Db2ConnectionFactory;
import br.org.credfaz.ficha.modelo.ContaCorrente;

public class ContaCorrenteDAO {

	private final Connection connection;

	public ContaCorrenteDAO() {
		try {
			connection = new Db2ConnectionFactory().getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public List<ContaCorrente> lista() {
		try {
			List<ContaCorrente> dbcliente = new ArrayList<ContaCorrente>();
		
			PreparedStatement stmt = this.connection
					.prepareStatement("select * from contacorrente")
					;
		
			ResultSet rs = stmt.executeQuery();


			while (rs.next()) {
				dbcliente.add(populaContaCorrente(rs));
			}

			rs.close();

			return dbcliente;

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public ContaCorrente buscaPorId(Long cc) {
		try {
			ContaCorrente dbcliente = new ContaCorrente();

			PreparedStatement stmt = this.connection
					.prepareStatement("select cc.numcontacorrente, cc.dataabertura,"
							+ "cc.valorsaldodispoant, cc.valorsaldodispopatual, cc.valorsaldodiaanterior, ex.valorlimite "
							+ "from "
							+ "contacapital ca, "
							+ "contacorrente cc, " 
							+ "extcontacorrente ex "
							+ "where ex.numcontacorrente = cc.numcontacorrente and cc.numcontacorrente = ca.numcontacorrente and ca.idcliente = ?");
			stmt.setLong(1, cc);

			ResultSet rs = stmt.executeQuery();

			if (rs.next()) {
				return populaContaCorrente(rs);
			}

			rs.close();
			stmt.close();

			return dbcliente;

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private ContaCorrente populaContaCorrente(ResultSet rs) throws SQLException {

		ContaCorrente cc = new ContaCorrente();

		cc.setNumcontacorrente(rs.getLong("numcontacorrente"));
		cc.setDataabertura(rs.getDate("dataabertura"));
		cc.setValorsaldodispoant(rs.getDouble("valorsaldodispoant"));
		cc.setValorsaldodispopatual(rs.getDouble("valorsaldodispopatual"));
		cc.setValorsaldodiaanterior(rs.getDouble("valorsaldodiaanterior"));
		cc.setValorlimite(rs.getDouble("valorlimite"));
		

		return cc;
	}

	
	

}
